<?php

use Doraemon\tools\Log;

abstract class QueueActionPlugin extends Yaf_Action_Abstract
{

    const LOGIN_AUTH = true;

    const CODE_SUCCESS = 1;

    const CODE_NOT_RETRY = -1;

    abstract public function main();

    public function execute()
    {
        $this->getResponse()->setHeader('Content-Type', 'application/json;charset=utf8');
        try {
            $this->checkModules();
            $this->main();
            Log::queue_execSuccess_debug(static::class, [
                "uri" => $this->getRequest()->getRequestUri(),
                "params" => $this->getRequest()->getPost()
            ]);
        } catch (\Exception $e) {
            Log::queue_execError_error(static::class, [
                "uri" => $this->getRequest()->getRequestUri(),
                "params" => $this->getRequest()->getPost(),
                "error" => $e
            ]);
            $this->setError($e->getCode(), $e->getMessage(), $e->getLine());
        }
    }

    protected function checkModules()
    {
        if (isset($_SERVER['APP_MODULES'])) {
            $authorizedModules = explode(",", $_SERVER['APP_MODULES']);
            if (!in_array($this->getModuleName(), $authorizedModules)) {
                throw new \Exception("当前域名不能请求当前模块");
            }
        }
    }

    protected function setSuccess($data = NULL)
    {
        $this->getResponse()->setBody(json_encode([
            "code" => self::CODE_SUCCESS,
            "data" => $data
        ], JSON_UNESCAPED_UNICODE));
    }

    protected function setError($code, $message, $line = 0)
    {
        $from = $this->getRequest()->getPost("from");


        if(empty($from)){
            if ($code == self::CODE_NOT_RETRY) {
                $view = [
                    "code" => self::CODE_SUCCESS,
                    "msg" => $message
                ];
            } else {
                $view = [
                    "code" => $line,
                    "msg" => $message
                ];
            }
        }else{
            $view = [
                "code" => -2,//有来源方向的区别有错误异常的code
                "msg" => $message
            ];
        }

        $this->getResponse()->setBody(json_encode($view, JSON_UNESCAPED_UNICODE));
    }
}
